package top.frsf.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import top.frsf.entity.Visit;
import top.frsf.service.VisitService;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author FRSF
 * @Date 2022/6/30 14:10
 * @Description
 **/

@Component
public class VisitInterceptor implements HandlerInterceptor {

    @Autowired
    private VisitService visitService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String remoteAddr = request.getRemoteAddr();
        if (!StringUtils.hasText(remoteAddr)) return false;
        Visit visit = new Visit();
        visit.setIp(remoteAddr);
        List<Visit> visitByIp = visitService.getVisitByIp(visit);
        if (visitByIp.isEmpty()) {
            visit.setCount(1);
            visitService.insert(visit);
        } else {
            visitByIp.get(0).setCount(visitByIp.get(0).getCount() + 1);
            visitService.update(visitByIp.get(0));
        }
        return true;
    }
}
